package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLogin;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 *用户端登录接口实现类
 */
@Service
@Slf4j
public class UserLoginImpl implements UserLogin {

    //微信登录接口地址
    public static final String KEY = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信用户端登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信登录接口，获取当前微信用户的openid
        HashMap<String,String> paramMap =new HashMap<String,String>();
        //拼接请求参数
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String json = httpClientUtil.doGet(KEY,paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("微信用户openid:{}",openid);

        //判断openid是否存在，不存在就抛出异常，登录失败
        if(openid == null){
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }
        //判断是否为新用户，
        User user  = userMapper.getByOpenid(openid);
        // 新用户自动完成注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }
}
